<?php

namespace app\controller\api\v1\agent;

use app\Request;
use app\services\agent\AgentLevelServices;
use app\services\agent\AgentLevelTaskServices;
use app\services\product\product\StoreProductLogServices;
use app\services\user\UserBrokerageServices;
use app\services\user\UserExtractServices;
use app\services\user\UserServices;
use app\services\wechat\WechatUserServices;
use think\annotation\Inject;

/**
 * 代理中心
 * Class Index
 * @package app\controller\api\v1\agent
 */
class Index
{
    /**
     * 分销用户详情
     * @param Request $request
     */
    public function getAgentInfo(Request $request)
    {
        /** @var AgentLevelServices $agentLevelServices */
        $agentLevelServices = app()->make(AgentLevelServices::class);
        $data = $agentLevelServices->getUserlevelList2((int)$request->uid());
        return app('json')->successful($data);
    }

    /**
     * 查看升级条件
     * @param Request $request
     */
    public function getUpgradeConditions(Request $request)
    {
        /** @var AgentLevelTaskServices $agentLevelTaskServices */
        $agentLevelTaskServices = app()->make(AgentLevelTaskServices::class);
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        $user = $userServices->getUserCacheInfo((int)$request->uid());
        $data = $agentLevelTaskServices->getUserLevelTaskList((int)$request->uid(), (int)$user['agent_level']);
        return app('json')->successful($data);
    }

    /**
     * 统计数据--订单/销售额/差价总额/新增代理商/结算佣金/销售奖励
     * @param type:1=今日,2=昨日,3=7天,4=30天
     * @param Request $request
     */
    public function getStaticData(Request $request)
    {
        $where = $request->getMore([
            ['type', 0]
        ]);

        $data = [
            'order_num' => 0,
            'sale_amount' => 0.00,
            'diff_amount' => 0.00,
            'add_people'  => 0,
            'settlement_commission' => 0.00,
            'sales_rewards' => 0.00
        ];
        return app('json')->successful($data);
    }

    public function receiveTarget(Request $request)
    {
        return app('json')->successful('领取成功!');
    }

    public function targetStatus(Request $request)
    {
        $data = [
            'receive_status' => false,
            'receive_status_text' => '点击领取本月指标'
        ];
        return app('json')->successful($data);
    }

    /**
     * 全球分红数据
     * @param Request $request
     * @return \think\Response
     */
    public function getBonusData(Request $request)
    {
        $data = [
            'month_achievement' =>0.00,
            'next_achievement' => 0.00,
            'diff_achievement' => 0.00,
            'commission_rate'  => 2,
            'next_commission_rate' => 3
        ];
        return app('json')->successful($data);
    }


    public function getTeamCommission(Request $request)
    {

        $where = $request->getMore([
            ['type', 0]
        ]);
        $data = [
            'level' => "品牌大使",
            'team_achievement' => 0.00,
            'commission' => 0.00,
            'consume_amount' => 0.00
        ];
        return app('json')->successful($data);

    }

    /**
     * 佣金记录
     * @param int $page
     * @param int $limit
     * @param Request $request
     */
    public function getCommissionList(Request $request)
    {
        $where = $request->getMore([
            ['start', 0],
            ['stop', 0],
            ['keyword', '']
        ]);
        $uid = (int)$request->uid();
        /** @var UserBrokerageServices $services */
        $services = app()->make(UserBrokerageServices::class);
        $data = $services->userBrokerageList($uid, $where);
        return app('json')->successful($data);
    }

    /**
     * 提现记录
     * @param Request $request
     * @return \think\Response
     */

    public function getWithdrawList(Request $request)
    {
        $where = $request->getMore([
            ['start', 0],
            ['stop', 0],
            ['keyword', '']
        ]);
        $uid = (int)$request->uid();
        /** @var UserBrokerageServices $services */
        $services = app()->make(UserBrokerageServices::class);
        $data = $services->userExtractList($uid, $where);
        return app('json')->successful($data);
    }

    /**
     * 我的团队
     * @param Request $request
     * @return \think\Response
     */
    public function getMyTeam(Request $request)
    {
        $spreadInfo = $request->getMore([
            ['grade', 0],
            ['keyword', ''],
            ['sort', ''],
            ['start', 0],
            ['stop', 0],
            ['is_direct',0],
            ['is_interrelated',0],
            ['is_flat_level',0]
        ]);
        $data = [
            "total" =>2,
            "totalLevel"=>0,
            "levelList" => [
                ["id"=>0,"name"=>'全部'],
                ["id"=>1,"name"=>'vip'],
                ["id"=>3,"name"=>'svip'],
            ],
            "list" => [
                [
                    "uid"=> 2,
                    "nickname"=>"1522ff7603d4",
                    "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",
                    "phone" => '17767676767',
                    "time"=> "2024/07/24",
                    'spread_uid' => 12331,
                    "spread_time"=> 0,
                    'level' => 'svip',
                    'spread_user' => 'zjt',
                    "childCount"=> 0,
                    "orderCount"=> 2,
                    "numberCount"=> "11.00",
                    "is_direct" => true,
                    "is_flat_level" => true,
                ],
                [
                    "uid"=> 1,
                    "nickname"=> "wx126789",
                    "phone" => '17767676767',
                    "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",
                    "time"=> "2024/07/19",
                    'spread_uid' => 12331,
                    'spread_user' => 'zjt',
                    'level' => 'svip',
                    "spread_time"=> 0,
                    "childCount"=> 0,
                    "orderCount"=> 4,
                    "numberCount"=> "19.00",
                    "is_direct" => false,
                    "is_flat_level" => false,
                ]
            ],
            "brokerage_level"=> 2,
            "count"=> 2,
            "price"=>0,
            "commission"=>0,
            "agent_count"=>0,
            "order_count" =>0
        ];
        return app('json')->successful($data);
        if (!in_array($spreadInfo['grade'], [0, 1])) {
            return app('json')->fail('等级错误');
        }
        $spreadInfo['time'] = [$spreadInfo['start'], $spreadInfo['stop']];
        $uid = $request->uid();
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        $data = $userServices->getUserSpreadGrade($uid, $spreadInfo['grade'], $spreadInfo['sort'], $spreadInfo['keyword'], $spreadInfo['time']);
        return app('json')->successful($data);
    }


    /**
     * 提现银行列表
     * @param Request $request
     * @return mixed
     */
    public function getBankList(Request $request)
    {
        $uid = (int)$request->uid();
        $userExtractServices = app()->make(UserExtractServices::class);
        return app('json')->successful($userExtractServices->bank($uid));
    }

    /**
     * 提现申请
     * @param Request $request
     * @return mixed
     */
    public function addWithdraw(Request $request)
    {
        $extractInfo = $request->postMore([
            ['alipay_code', ''],
            ['extract_type', 'bank'],
            ['money', 0],
            ['name', ''],
            ['bankname', ''],
            ['cardnum', ''],
            ['weixin', ''],
            ['qrcode_url', ''],
        ]);
        $extractType = Config::get('pay.extractType', []);
        if (!in_array($extractInfo['extract_type'], $extractType))
            return app('json')->fail('提现方式不存在');
        if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', (float)$extractInfo['money'])) return app('json')->fail('提现金额输入有误');
        if (!$extractInfo['cardnum'] == '')
            if (!preg_match('/^([1-9]{1})(\d{15}|\d{16}|\d{18})$/', $extractInfo['cardnum']))
                return app('json')->fail('银行卡号输入有误');
        if ($extractInfo['extract_type'] == 'alipay') {
            if (!$extractInfo['alipay_code']) return app('json')->fail('请输入支付宝账号');
        } else if ($extractInfo['extract_type'] == 'bank') {
            if (!$extractInfo['cardnum']) return app('json')->fail('请输入银行卡账号');
            if (!$extractInfo['bankname']) return app('json')->fail('请输入开户行信息');
        } else if ($extractInfo['extract_type'] == 'weixin' && sys_config('brokerage_type') == 0) {
            if (!$extractInfo['weixin']) return app('json')->fail('请输入微信账号');
        }
        $uid = (int)$request->uid();
        /** @var UserExtractServices $userExtractServices */
        $userExtractServices = app()->make(UserExtractServices::class);
        $result = $userExtractServices->cash($uid, $extractInfo);
        if ($result)
            return app('json')->successful('申请提现成功!');
        else
            return app('json')->fail('提现失败');
    }

    /**
     * 获取用户推广用户列表
     * @param type:0
     * @param Request $request
     * @param UserServices $userServices
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function agentUserList(Request $request, UserServices $userServices)
    {
        [$type] = $request->getMore([
            ['type', 0]
        ], true);
        $uid = $request->uid();
        $data = [
            "list" => [
                [
                    "uid"=> 2,
                    "nickname"=>"1522ff7603d4",
                    "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",
                    "phone" => '17767676767',
                    "spread_time"=> "2024/07/24",
                    "is_write" => true
                ],
                [
                    "uid"=> 1,
                    "nickname"=> "wx126789",
                    "phone" => '17767676767',
                    "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",
                    "spread_time"=> "2024/07/19",
                    "is_write" => false

                ]
            ],
            "count"=> 2
        ];
        return app('json')->successful($data);
        return app('json')->successful($userServices->agentUserList($uid, $type));
    }

    /**
     * 申请成为代理
     * @param Request $request
     */
    public function apply(Request $request)
    {
        $extractInfo = $request->postMore([
            ['nickname', ''],
            ['mobile', ''],
            ['city', ''],
            ['code', '']
        ]);
        return app('json')->successful(['msg'=>'申请成为代理']);
    }

    /**
     * 保证金列表
     * @param Request $request
     * @return \think\Response
     */
    public function getBondList(Request $request)
    {
        $where = $request->getMore([
            ['start', 0],
            ['stop', 0],
            ['keyword', '']
        ]);
        $data = [
            [
                "id"=> 2,
                "type" => "提现",

                "time"=> "2024/07/24",

                "money" => '20.00',

            ],
            [
                "id"=> 3,
                "type" => "消费储值",

                "time"=> "2024/07/24",

                "money" => '20.00',
            ]
        ];
        $result = [
            'list'  => $data,
            'left_bond' => 1110.00,
            'withdraw_bond' => 22232.00,
            'count' => 3
        ];
        return app('json')->successful($result);
        $uid = (int)$request->uid();
        /** @var UserMoneyServices $services */
        $services = app()->make(UserMoneyServices::class);
        $data = $services->userMoneyList($uid,2, $where);
        return app('json')->successful($data);
    }

    /**
     * 排行
     * @param Request $request
     * @return mixed
     */
    public function rank(Request $request)
    {

        $data = $request->getMore([
            ['page', ''],
            ['limit'],
            ['type'],
            ['date_type','']
        ]);
        $data = [
            "levelList" => [
                ["id"=>0,"name"=>'全部'],
                ["id"=>1,"name"=>'vip'],
                ["id"=>3,"name"=>'svip'],
            ],
            "list" =>[ [
                "uid"=> 2,
                "nickname"=>"1522ff7603d4",
                "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",

                "order_count" => 10,

                "money" => '20.00',

            ],
                [
                    "uid"=> 3,
                    "nickname"=>"3333",
                    "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",

                    "order_count" => 9,

                    "money" => '10.00',
                ]
            ],
            'count' => 3
        ];
        return app('json')->success($data);
        $uid = (int)$request->uid();
        $userInfo = $request->user();
        /** @var UserBrokerageServices $services */
        $services = app()->make(UserBrokerageServices::class);
        $data = $services->brokerage_rank($uid, $data['type']);
        $data['nickname'] = $userInfo['nickname'];
        $data['avatar'] = $userInfo['avatar'];
        return app('json')->success($data);
    }
    /**
     * 排行
     * @param Request $request
     * @return mixed
     */
    public function getBonusDetailList(Request $request)
    {
        $where = $request->getMore([
            ['year', '']
        ]);
        $data = [
            [
                'month' => '6月',
                'sale_amount' => 1000.00,
                'commission_rate' => '6%',
                'commission' => 20.00,
                'is_withdraw' => false,
                'withdraw_date' => ''
            ],
            [
                'month' => '7月',
                'sale_amount' => 10000.00,
                'commission_rate' => '6%',
                'commission' => 20.00,
                'is_withdraw' => true,
                'withdraw_date' => '2024-08-20'
            ]
        ];
        $result = [
            'lists'=>$data,
            'month_income' => 200.00,
            'month_pending_income' => 300.00,
            'total_income' => 10000.00,
            'count' => 1
        ];
        return app('json')->successful($result);
    }

    public function getBonusDetailByMonth(Request $request)
    {
        $where = $request->getMore([
            ['year', ''],
            ['month', ''],
        ]);
        $data = [
            [
                "uid"=> 3,
                "nickname"=>"3333",
                "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",
                'sale_amount' => 1000.00,
                'commission_rate' => '6%',
                'commission' => 20.00,

            ],
            [
                "uid"=> 4,
                "nickname"=>"3333",
                "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",
                'sale_amount' => 1000.00,
                'commission_rate' => '6%',
                'commission' => 20.00,
            ]
        ];
        $result = [
            'lists'=>$data,
            'total_income' => 10000.00,
            'count' => 1
        ];
        return app('json')->successful($result);
    }

    public function getTeamOrderList(Request $request)
    {
        $where = $request->getMore([
            ['is_flat_level',0],
            ['start', 0],
            ['stop', 0]
        ]);
        $data = [
            [
                "uid"=> 2,
                "nickname"=>"1522ff7603d4",
                "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",

                "time"=> "2024/07/24",

                "money" => '20.00',
                "status" => 1,
                "status_text"=>"等待商家发货",
                "goods_id" => 1,

                "commission" =>2.00,
                "order_id" => "2023290w9w02932320",
                "settle_status" => 1,
                "settle_status_text" => "待结算"
            ],
            [
                "uid"=> 2,
                "nickname"=>"1522ff7603d4",
                "avatar"=> "http://zjt.0598qq.com/uploads/system/723adbdd4e49a0f9394dfc700ab5dba3.png",

                "time"=> "2024/07/24",

                "money" => '20.00',
                "status" => 1,
                "status_text"=>"等待商家发货",
                "goods_id" => 2,

                "commission" =>2.00,
                "order_id" => "2023290w9w029323202",
                "settle_status" => 1,
                "settle_status_text" => "待结算"
            ]
        ];
        $result = [
            'list' => $data,
            'statusList' => [
                ['id'=>0,'name'=>'全部'],
                ['id'=>1,'name'=>'未付款']
            ],
            'count' => 2
        ];
        return app('json')->successful($result);
    }
}